import { useState, useRef, useEffect, useCallback } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import GiftPanel from './GiftPanel';
import RechargeModal from './RechargeModal';

// 模拟直播列表数据，真实项目中可以从API获取
const liveRoomList = [
  {
    id: 101,
    anchor: { name: 'LISA', level: 8, avatar: 'https://randomuser.me/api/portraits/women/44.jpg' },
    viewer: 50500,
    video: '/meinv.mp4'
  },
  {
    id: 102,
    anchor: { name: '晴天', level: 9, avatar: 'https://randomuser.me/api/portraits/women/42.jpg' },
    viewer: 33800,
    video: '/meinv.mp4'
  },
  {
    id: 103,
    anchor: { name: '小白兔', level: 7, avatar: 'https://randomuser.me/api/portraits/women/43.jpg' },
    viewer: 29600,
    video: '/meinv.mp4'
  },
  {
    id: 104,
    anchor: { name: '艺术家', level: 10, avatar: 'https://randomuser.me/api/portraits/men/41.jpg' },
    viewer: 65200,
    video: '/meinv.mp4'
  }
];

const userName = '小明';
const userAvatar = 'https://randomuser.me/api/portraits/men/11.jpg';
const initialMessages = [
  { id: 1, avatar: userAvatar, nick: '牙齿很痛', level: 5, levelColor: '#ffecb3', content: '送入小红花', gift: { icon: '🌹', count: 16 } },
  { id: 2, avatar: userAvatar, nick: 'check now', level: 2, levelColor: '#b3e6ff', content: '来一次' },
  { id: 3, avatar: userAvatar, nick: '刘聪的Key', level: 8, levelColor: '#ffd700', content: '台北下了雪，你说那是玛丽龙。' }
];
const viewers = [
  'https://randomuser.me/api/portraits/women/1.jpg',
  'https://randomuser.me/api/portraits/men/2.jpg',
  'https://randomuser.me/api/portraits/women/3.jpg',
  'https://randomuser.me/api/portraits/men/4.jpg'
];
const giftList = [
  { icon: '🌹', name: '爱心玫瑰', price: 10 },
  { icon: '💎', name: '钻石', price: 50 },
  { icon: '🚗', name: '跑车', price: 200 },
  { icon: '👑', name: '皇冠', price: 500 },
  { icon: '🎁', name: '礼物盒', price: 30 },
  { icon: '🎤', name: '麦克风', price: 20 },
  { icon: '🎸', name: '吉他', price: 100 }
];

// 随机评论内容数组
const randomComments = [
  '主播好漂亮啊！',
  '这个妆容太美了',
  '求推荐口红色号',
  '主播唱首歌吧',
  '主播今天心情怎么样？',
  '这个衣服在哪买的？',
  '主播多久直播一次？',
  '这个背景音乐是什么歌？',
  '主播笑起来真好看',
  '这个发型真适合你',
  '主播今天状态超好',
  '刚来，错过了什么？',
  '主播能站起来看看全身搭配吗？',
  '主播平时都用什么护肤品？',
  '这个角度拍得真好',
  '主播能介绍一下你的设备吗？',
  '这个滤镜效果真不错',
  '主播多大了呀？',
  '主播能推荐一下减肥方法吗？',
  '这个直播间氛围真好'
];

// 随机用户昵称数组
const randomUsers = [
  { nick: '星空漫步', level: 3, avatar: 'https://randomuser.me/api/portraits/women/20.jpg', levelColor: '#b3e6ff' },
  { nick: '梦幻精灵', level: 5, avatar: 'https://randomuser.me/api/portraits/men/21.jpg', levelColor: '#ffecb3' },
  { nick: '夏日微风', level: 2, avatar: 'https://randomuser.me/api/portraits/women/22.jpg', levelColor: '#b3e6ff' },
  { nick: '海洋之心', level: 7, avatar: 'https://randomuser.me/api/portraits/men/23.jpg', levelColor: '#ffd700' },
  { nick: '云端漫步', level: 4, avatar: 'https://randomuser.me/api/portraits/women/24.jpg', levelColor: '#b3e6ff' },
  { nick: '花开富贵', level: 6, avatar: 'https://randomuser.me/api/portraits/men/25.jpg', levelColor: '#ffecb3' },
  { nick: '冰雪奇缘', level: 3, avatar: 'https://randomuser.me/api/portraits/women/26.jpg', levelColor: '#b3e6ff' },
  { nick: '阳光男孩', level: 8, avatar: 'https://randomuser.me/api/portraits/men/27.jpg', levelColor: '#ffd700' },
  { nick: '甜心宝贝', level: 4, avatar: 'https://randomuser.me/api/portraits/women/28.jpg', levelColor: '#b3e6ff' },
  { nick: '酷炫少年', level: 5, avatar: 'https://randomuser.me/api/portraits/men/29.jpg', levelColor: '#ffecb3' }
];

export default function LiveRoom() {
  const navigate = useNavigate();
  const { id } = useParams(); // 获取当前直播间ID
  const currentLiveId = parseInt(id || '101');
  
  // 找到当前直播间信息
  const currentLive = liveRoomList.find(live => live.id === currentLiveId) || liveRoomList[0];
  
  // 计算前一个和后一个直播间的ID
  const liveRoomIndex = liveRoomList.findIndex(live => live.id === currentLiveId);
  const prevLiveId = liveRoomIndex > 0 ? liveRoomList[liveRoomIndex - 1].id : liveRoomList[liveRoomList.length - 1].id;
  const nextLiveId = liveRoomIndex < liveRoomList.length - 1 ? liveRoomList[liveRoomIndex + 1].id : liveRoomList[0].id;
  
  const [messages, setMessages] = useState(initialMessages);
  const [input, setInput] = useState("");
  const [showGiftPanel, setShowGiftPanel] = useState(false);
  const [showRecharge, setShowRecharge] = useState(false);
  const [balance, setBalance] = useState(0);
  const [giftAnims, setGiftAnims] = useState([]);
  const [lastGift, setLastGift] = useState(null);
  const [showLike, setShowLike] = useState(false);
  // 视频连线相关
  const [showLinkModal, setShowLinkModal] = useState(false);
  const [localStream, setLocalStream] = useState(null);
  const [videoEnabled, setVideoEnabled] = useState(true);
  const [audioEnabled, setAudioEnabled] = useState(true);
  const videoRef = useRef(null);
  const [isFollowed, setIsFollowed] = useState(false);
  const [tip, setTip] = useState('');
  const [showUnfollowModal, setShowUnfollowModal] = useState(false);
  const [showViewerList, setShowViewerList] = useState(false);
  const commentsRef = useRef(null);
  // 添加确认离开直播间的弹窗状态
  const [showExitConfirm, setShowExitConfirm] = useState(false);
  // 添加切换动画状态
  const [switchDirection, setSwitchDirection] = useState(null); // 'up' 或 'down' 或 null
  // 添加鼠标滚动相关状态
  const [isScrolling, setIsScrolling] = useState(false);
  const [startY, setStartY] = useState(0);
  const [currentY, setCurrentY] = useState(0);
  const scrollThreshold = 100; // 滚动阈值，超过这个值才会触发切换
  
  const [onlineViewers, setOnlineViewers] = useState([
    { avatar: 'https://randomuser.me/api/portraits/women/1.jpg', name: '小美', giftAmount: 520, level: 8, giftCount: 3, anim: false },
    { avatar: 'https://randomuser.me/api/portraits/men/2.jpg', name: '阿强', giftAmount: 0, level: 2, giftCount: 0, anim: false },
    { avatar: 'https://randomuser.me/api/portraits/women/3.jpg', name: '小红', giftAmount: 88, level: 5, giftCount: 1, anim: false },
    { avatar: 'https://randomuser.me/api/portraits/men/4.jpg', name: '大壮', giftAmount: 188, level: 6, giftCount: 2, anim: false },
    { avatar: 'https://randomuser.me/api/portraits/men/5.jpg', name: '小明', giftAmount: 0, level: 1, giftCount: 0, anim: false },
    { avatar: 'https://randomuser.me/api/portraits/women/6.jpg', name: '小芳', giftAmount: 66, level: 4, giftCount: 1, anim: false },
    { avatar: 'https://randomuser.me/api/portraits/men/7.jpg', name: '小李', giftAmount: 0, level: 2, giftCount: 0, anim: false },
    { avatar: 'https://randomuser.me/api/portraits/women/8.jpg', name: '小丽', giftAmount: 999, level: 10, giftCount: 5, anim: false },
    { avatar: 'https://randomuser.me/api/portraits/men/9.jpg', name: '小王', giftAmount: 0, level: 3, giftCount: 0, anim: false },
    { avatar: 'https://randomuser.me/api/portraits/women/10.jpg', name: '小雪', giftAmount: 10, level: 2, giftCount: 1, anim: false },
  ]);
  // 添加自动生成评论的开关
  const [autoCommentEnabled, setAutoCommentEnabled] = useState(true);

  // 处理返回按钮点击事件
  const handleBackClick = () => {
    // 显示确认对话框
    setShowExitConfirm(true);
  };
  
  // 确认离开直播间
  const confirmExit = () => {
    // 先显示提示
    setTip('正在返回发现页面...');
    
    // 如果有视频连线，先停止连线
    if (localStream) {
      handleStopLink();
    }
    
    // 延迟一小段时间再返回，让用户看到提示
    setTimeout(() => {
      // 返回到发现页面
      navigate('/discover');
    }, 300);
  };
  
  // 取消离开直播间
  const cancelExit = () => {
    setShowExitConfirm(false);
  };

  // 处理切换直播间
  const switchLiveRoom = useCallback((direction) => {
    // 如果正在滚动或已有弹窗打开，则不切换
    if (isScrolling || showGiftPanel || showRecharge || showLinkModal || 
        showViewerList || showExitConfirm || showUnfollowModal) {
      return;
    }
    
    // 设置正在滚动状态，防止频繁切换
    setIsScrolling(true);
    
    // 如果有视频连线，先停止连线
    if (localStream) {
      handleStopLink();
    }
    
    // 设置切换方向，触发动画
    setSwitchDirection(direction);
    
    // 提示正在切换直播间
    setTip(direction === 'up' ? '正在切换到上一个直播间...' : '正在切换到下一个直播间...');
    
    // 延迟导航，让动画有时间显示
    setTimeout(() => {
      const targetId = direction === 'up' ? prevLiveId : nextLiveId;
      navigate(`/live/${targetId}`);
      
      // 重置切换方向和滚动状态
      setSwitchDirection(null);
      setIsScrolling(false);
    }, 500);
  }, [navigate, prevLiveId, nextLiveId, localStream, isScrolling, showGiftPanel, showRecharge, showLinkModal, showViewerList, showExitConfirm, showUnfollowModal]);

  // 处理鼠标点击事件 - 可以完全移除，但保留函数体以备将来使用
  const handleClick = useCallback((e) => {
    // 现在这个函数仅检查是否点击在控制元素上
    // 保留这个函数以便将来可能的扩展
    if (e.target.closest('.control-element') || 
        showGiftPanel || showRecharge || showLinkModal || 
        showViewerList || showExitConfirm || showUnfollowModal) {
      return;
    }
  }, [showGiftPanel, showRecharge, showLinkModal, showViewerList, showExitConfirm, showUnfollowModal]);

  // 处理鼠标按下事件
  const handleMouseDown = useCallback((e) => {
    // 排除点击在控制元素上的情况
    if (e.target.closest('.control-element') || 
        showGiftPanel || showRecharge || showLinkModal || 
        showViewerList || showExitConfirm || showUnfollowModal) {
      return;
    }
    
    // 只处理鼠标左键按下事件
    if (e.button === 0) {
      // 记录鼠标按下的初始位置
      setIsScrolling(true);
      setStartY(e.clientY);
      setCurrentY(e.clientY);
    }
  }, [showGiftPanel, showRecharge, showLinkModal, showViewerList, showExitConfirm, showUnfollowModal]);
  
  // 处理鼠标移动事件
  const handleMouseMove = useCallback((e) => {
    // 只有在滚动状态时才处理鼠标移动
    if (!isScrolling) {
      // 不再显示滑动提示，因为我们现在只使用左键拖动
      return;
    }
    
    // 更新当前鼠标位置
    setCurrentY(e.clientY);
  }, [isScrolling]);
  
  // 处理鼠标松开事件
  const handleMouseUp = useCallback(() => {
    if (!isScrolling) return;
    
    // 计算滑动距离
    const distance = currentY - startY;
    
    // 滑动距离超过阈值，切换直播间
    if (Math.abs(distance) > scrollThreshold) {
      if (distance > 0) {
        // 向下滑动，切换到下一个直播间
        switchLiveRoom('down');
      } else {
        // 向上滑动，切换到上一个直播间
        switchLiveRoom('up');
      }
    }
    
    // 重置滚动状态
    setIsScrolling(false);
  }, [isScrolling, currentY, startY, scrollThreshold, switchLiveRoom]);
  
  // 处理鼠标滚轮事件 - 简化为空函数
  const handleWheel = useCallback(() => {
    // 滚轮总是被禁用，因为我们现在只使用左键拖动
    // 所以直接返回，不执行任何操作
    return;
  }, []);
  
  // 绑定鼠标事件
  useEffect(() => {
    window.addEventListener('mousedown', handleMouseDown);
    window.addEventListener('mousemove', handleMouseMove);
    window.addEventListener('mouseup', handleMouseUp);
    window.addEventListener('wheel', handleWheel, { passive: true });
    window.addEventListener('click', handleClick);
    
    return () => {
      window.removeEventListener('mousedown', handleMouseDown);
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('mouseup', handleMouseUp);
      window.removeEventListener('wheel', handleWheel);
      window.removeEventListener('click', handleClick);
      
      // 删除不再需要的清理代码
      // if (wheelStatusTimerRef.current) {
      //   clearTimeout(wheelStatusTimerRef.current);
      // }
    };
  }, [handleMouseDown, handleMouseMove, handleMouseUp, handleWheel, handleClick]);

  // 发送弹幕
  const handleSend = (e) => {
    e.preventDefault();
    if (!input.trim()) return;
    setMessages(msgs => [...msgs, {
      id: Date.now(),
      avatar: userAvatar,
      nick: userName,
      level: 6,
      levelColor: '#b3e6ff',
      content: input.trim()
    }]);
    setInput("");
  };

  // 发送礼物
  const handleSendGift = (gift) => {
    if (balance < gift.price) {
      setShowGiftPanel(false);
      setShowRecharge(true);
      return;
    }
    setBalance(bal => bal - gift.price);
    // 更新观众送礼金额、次数和动画
    setOnlineViewers(viewers =>
      viewers.map(v =>
        v.name === userName
          ? { ...v, giftAmount: v.giftAmount + gift.price, giftCount: (v.giftCount || 0) + 1, anim: true }
          : v
      )
    );
    setTimeout(() => {
      setOnlineViewers(viewers => viewers.map(v => ({ ...v, anim: false })));
    }, 800);
    if (lastGift && lastGift.user === userName && lastGift.gift === gift.name) {
      setLastGift({ ...lastGift, count: lastGift.count + 1 });
      setGiftAnims(anims => [...anims, { ...gift, id: Date.now(), user: userName, avatar: userAvatar, count: lastGift.count + 1 }]);
      setMessages(msgs => [...msgs, { id: Date.now(), avatar: userAvatar, nick: userName, level: 6, levelColor: '#b3e6ff', content: `连续送出${lastGift.count + 1}个${gift.name}`, gift: { icon: gift.icon, count: lastGift.count + 1 } }]);
    } else {
      setLastGift({ user: userName, gift: gift.name, count: 1 });
      setGiftAnims(anims => [...anims, { ...gift, id: Date.now(), user: userName, avatar: userAvatar, count: 1 }]);
      setMessages(msgs => [...msgs, { id: Date.now(), avatar: userAvatar, nick: userName, level: 6, levelColor: '#b3e6ff', content: `送出了${gift.name}`, gift: { icon: gift.icon, count: 1 } }]);
    }
    setTimeout(() => {
      setGiftAnims(anims => anims.slice(1));
    }, 1500);
  };

  // 充值成功回调
  const handleRecharge = (amount) => {
    setBalance(bal => bal + amount);
    setShowRecharge(false);
  };

  // 点赞动画
  const handleLike = () => {
    setShowLike(true);
    setTimeout(() => setShowLike(false), 800);
  };

  // 视频连线相关逻辑
  const handleStartLink = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
      setLocalStream(stream);
      setShowLinkModal(false);
      setVideoEnabled(true);
      setAudioEnabled(true);
    } catch {
      alert('无法获取摄像头/麦克风权限');
    }
  };
  const handleStopLink = () => {
    if (localStream) {
      localStream.getTracks().forEach(track => track.stop());
      setLocalStream(null);
    }
  };
  const toggleVideo = () => {
    if (localStream) {
      localStream.getVideoTracks().forEach(track => {
        track.enabled = !videoEnabled;
      });
      setVideoEnabled(v => !v);
    }
  };
  const toggleAudio = () => {
    if (localStream) {
      localStream.getAudioTracks().forEach(track => {
        track.enabled = !audioEnabled;
      });
      setAudioEnabled(a => !a);
    }
  };

  // 关键：localStream变化时赋值给video标签
  useEffect(() => {
    if (localStream && videoRef.current) {
      videoRef.current.srcObject = localStream;
    }
  }, [localStream]);

  const handleFollowClick = () => {
    if (!isFollowed) {
      setIsFollowed(true);
      setTip('关注成功！');
      setTimeout(() => setTip(''), 2000);
    } else {
      setShowUnfollowModal(true);
    }
  };
  const handleUnfollow = () => {
    setIsFollowed(false);
    setTip('已取消关注');
    setShowUnfollowModal(false);
    setTimeout(() => setTip(''), 2000);
  };

  // 添加自动滚动效果
  useEffect(() => {
    if (commentsRef.current) {
      // 滚动到底部，显示最新消息
      commentsRef.current.scrollTop = commentsRef.current.scrollHeight;
    }
  }, [messages]); // 当消息列表更新时触发

  // 添加自动生成随机评论的功能
  useEffect(() => {
    let commentInterval;
    
    // 只有当自动评论功能开启时才执行
    if (autoCommentEnabled) {
      commentInterval = setInterval(() => {
        // 随机选择一个用户
        const randomUser = randomUsers[Math.floor(Math.random() * randomUsers.length)];
        // 随机选择一条评论
        const randomComment = randomComments[Math.floor(Math.random() * randomComments.length)];
        
        // 添加新评论
        setMessages(msgs => [...msgs, {
          id: Date.now(),
          avatar: randomUser.avatar,
          nick: randomUser.nick,
          level: randomUser.level,
          levelColor: randomUser.levelColor,
          content: randomComment
        }]);
        
        // 如果消息超过50条，则删除最早的消息以避免内存占用过多
        setMessages(msgs => msgs.length > 50 ? msgs.slice(-50) : msgs);
        
      }, 2000); // 每2秒生成一条新评论
    }
    
    // 清理函数
    return () => {
      if (commentInterval) {
        clearInterval(commentInterval);
      }
    };
  }, [autoCommentEnabled]); // 当自动评论开关状态变化时重新设置

  return (
    <div style={{height:'100vh',background:'#222',color:'#fff',position:'relative',overflow:'hidden'}}>
      {/* 切换动画 */}
      {switchDirection && (
        <div 
          style={{
            position: 'absolute',
            left: 0,
            top: 0,
            right: 0,
            bottom: 0,
            background: 'rgba(0,0,0,0.5)',
            zIndex: 1000,
            animation: `slide-${switchDirection} 0.5s ease-in-out`,
          }}
        />
      )}
      
      {/* 滑动指示器 */}
      {isScrolling && Math.abs(currentY - startY) > 20 && (
        <div
          style={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: 'rgba(0,0,0,0.7)',
            borderRadius: '50%',
            width: 80,
            height: 80,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            zIndex: 100,
            opacity: Math.min(1, Math.abs(currentY - startY) / scrollThreshold * 0.8),
          }}
        >
          <div style={{fontSize: 24}}>
            {currentY - startY > 0 ? '↓' : '↑'}
          </div>
          <div style={{fontSize: 12}}>
            {Math.abs(currentY - startY) > scrollThreshold ? '松开切换' : '继续滑动'}
          </div>
        </div>
      )}
      
      {/* 顶部栏 */}
      <div className="control-element" style={{position:'absolute',top:0,left:0,right:0,zIndex:10,display:'flex',alignItems:'center',padding:'8px 10px',background:'rgba(0,0,0,0.25)'}}>
        {/* 添加返回按钮 */}
        <div style={{position: 'relative'}}>
          <button 
            className="control-element"
            onClick={handleBackClick}
            style={{
              background: 'rgba(0,0,0,0.3)',
              border: 'none',
              color: '#fff',
              fontSize: 22,
              cursor: 'pointer',
              marginRight: 12,
              width: 36,
              height: 36,
              borderRadius: '50%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              transition: 'all 0.3s',
              boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
            }}
            onMouseOver={(e) => {
              e.currentTarget.style.background = 'rgba(255,45,85,0.8)';
              e.currentTarget.style.transform = 'scale(1.1)';
              e.currentTarget.style.boxShadow = '0 4px 12px rgba(255,45,85,0.3)';
            }}
            onMouseOut={(e) => {
              e.currentTarget.style.background = 'rgba(0,0,0,0.3)';
              e.currentTarget.style.transform = 'scale(1)';
              e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.2)';
            }}
            onMouseDown={(e) => {
              e.currentTarget.style.transform = 'scale(0.95)';
            }}
            onMouseUp={(e) => {
              e.currentTarget.style.transform = 'scale(1.1)';
            }}
          >
            ←
          </button>
          {/* 悬停时显示的提示 */}
          <div 
            className="back-tooltip control-element"
            style={{
              position: 'absolute',
              top: '100%',
              left: '50%',
              transform: 'translateX(-50%)',
              background: 'rgba(0,0,0,0.7)',
              color: '#fff',
              padding: '4px 8px',
              borderRadius: '4px',
              fontSize: '12px',
              whiteSpace: 'nowrap',
              pointerEvents: 'none',
              opacity: 0,
              transition: 'opacity 0.2s',
              marginTop: '5px',
            }}
          >
            返回发现页面
          </div>
          <style>{`
            button:hover + .back-tooltip {
              opacity: 1;
            }
          `}</style>
        </div>
        <img src={currentLive.anchor.avatar} alt="主播" style={{width:36,height:36,borderRadius:'50%',marginRight:8}} />
        <div style={{flex:1}}>
          <div style={{fontWeight:'bold',fontSize:15}}>{currentLive.anchor.name} <span style={{fontSize:12,color:'#ffecb3',marginLeft:4}}>LV{currentLive.anchor.level}</span></div>
          <div style={{fontSize:12,color:'#fff'}}>{(currentLive.viewer / 10000).toFixed(1)}万本场点赞</div>
        </div>
        <button
          style={{
            background: isFollowed
              ? 'linear-gradient(90deg,#aaa,#ccc)'
              : 'linear-gradient(90deg,#ff2d55,#ff5e3a 80%)',
            color: '#fff',
            border: 'none',
            borderRadius: 18,
            padding: '6px 22px',
            fontWeight: 'bold',
            marginRight: 12,
            fontSize: 16,
            boxShadow: isFollowed
              ? '0 2px 8px #aaa4'
              : '0 2px 12px #ff2d5540',
            cursor: 'pointer',
            transition: 'all 0.2s cubic-bezier(.4,0,.2,1)',
            transform: tip ? 'scale(1.08)' : 'scale(1)'
          }}
          onClick={handleFollowClick}
          onMouseDown={e => e.currentTarget.style.transform = 'scale(0.95)'}
          onMouseUp={e => e.currentTarget.style.transform = tip ? 'scale(1.08)' : 'scale(1)'}
          onMouseLeave={e => e.currentTarget.style.transform = tip ? 'scale(1.08)' : 'scale(1)'}
        >
          {isFollowed ? '已关注' : '关注'}
        </button>
        {viewers.map((v) => (
          <img key={v} src={v} alt="" style={{width:28,height:28,borderRadius:'50%',border:'2px solid #222',marginLeft:-10}} />
        ))}
        <span
          style={{marginLeft:8,fontSize:13,color:'#fff',background:'#444',borderRadius:10,padding:'2px 8px',cursor:'pointer'}}
          onClick={()=>setShowViewerList(true)}
        >{onlineViewers.length}</span>
        <button style={{background:'none',border:'none',color:'#fff',fontSize:22,marginLeft:8}}>⋮</button>
      </div>
      {/* 在线观众列表弹窗 */}
      {showViewerList && (
        <div style={{position:'fixed',left:0,top:0,right:0,bottom:0,background:'rgba(0,0,0,0.45)',zIndex:300,display:'flex',alignItems:'center',justifyContent:'center'}}>
          <div style={{background:'#232323',borderRadius:'0.32rem',padding:'1.2rem 1.2rem 1rem 1.2rem',boxShadow:'0 4px 24px #0008',minWidth:'6rem',maxWidth:'90vw',textAlign:'center',maxHeight:'70vh',overflowY:'auto',position:'relative'}}>
            <button style={{position:'absolute',top:10,right:10,background:'none',border:'none',color:'#fff',fontSize:22,cursor:'pointer'}} onClick={()=>setShowViewerList(false)}>✕</button>
            <div style={{fontWeight:'bold',fontSize:'1.2em',marginBottom:18}}>在线观众（{onlineViewers.length}）</div>
            <div style={{display:'flex',flexDirection:'column',gap:16}}>
              {onlineViewers.slice().sort((a, b) => b.giftAmount - a.giftAmount).map((v, idx) => (
                <div key={v.avatar+v.name+idx} style={{display:'flex',alignItems:'center',gap:16,justifyContent:'space-between',background:'#292929',borderRadius:16,padding:'8px 16px'}}>
                  <div style={{display:'flex',alignItems:'center',gap:12}}>
                    <img src={v.avatar} alt={v.name} style={{width:38,height:38,borderRadius:20,marginRight:8,border:'2px solid #ff2d55'}} />
                    <span style={{fontSize:16,color:'#fff',marginRight:8}}>{v.name}</span>
                    <span style={{fontSize:13,color:'#ffd700',background:'#333',borderRadius:8,padding:'2px 8px',marginRight:8}}>Lv.{v.level}</span>
                    <span style={{fontSize:13,color:'#ff2d55',background:'#333',borderRadius:8,padding:'2px 8px'}}>送礼{v.giftCount}次</span>
                  </div>
                  <span style={{
                    fontSize:15,
                    color:v.giftAmount>0?'#ffecb3':'#aaa',
                    fontWeight:'bold',
                    minWidth:60,
                    textAlign:'right',
                    transition:'all 0.3s',
                    background:v.anim?'#fffbe6':'none',
                    borderRadius:v.anim?8:0,
                    boxShadow:v.anim?'0 0 8px #ffd700':'none',
                    animation:v.anim?'jump-amount 0.6s':''
                  }}>
                    ￥{v.giftAmount}
                  </span>
                </div>
              ))}
            </div>
            <style>{`
              @keyframes jump-amount {
                0% { transform: scale(1); }
                30% { transform: scale(1.3); }
                60% { transform: scale(0.95); }
                100% { transform: scale(1); }
              }
            `}</style>
          </div>
        </div>
      )}
      {/* 取消关注弹窗 */}
      {showUnfollowModal && (
        <div style={{position:'fixed',left:0,top:0,right:0,bottom:0,background:'rgba(0,0,0,0.45)',zIndex:200,display:'flex',alignItems:'center',justifyContent:'center'}}>
          <div style={{background:'#232323',borderRadius:'0.32rem',padding:'1.2rem 1.2rem 1rem 1.2rem',boxShadow:'0 4px 24px #0008',minWidth:'6rem',maxWidth:'90vw',textAlign:'center'}}>
            <div style={{fontWeight:'bold',fontSize:'1.2em',marginBottom:12}}>你确定取消关注该主播吗？</div>
            <div style={{display:'flex',gap:16,justifyContent:'center',marginTop:18}}>
              <button style={{background:'#ff2d55',color:'#fff',border:'none',borderRadius:'0.32rem',padding:'0.12rem 0.32rem',fontSize:'1em',fontWeight:'bold',minWidth:80}} onClick={handleUnfollow}>确定</button>
              <button style={{background:'#444',color:'#fff',border:'none',borderRadius:'0.32rem',padding:'0.12rem 0.32rem',fontSize:'1em',minWidth:80}} onClick={()=>setShowUnfollowModal(false)}>取消</button>
            </div>
          </div>
        </div>
      )}
      {/* 气泡提示 */}
      {tip && (
        <div style={{
          position: 'fixed',
          top: 24,
          right: 32,
          background: 'linear-gradient(90deg,#ff2d55,#ff5e3a 80%)',
          color: '#fff',
          borderRadius: 18,
          padding: '10px 24px',
          fontWeight: 'bold',
          fontSize: 16,
          boxShadow: '0 2px 12px #ff2d5540',
          zIndex: 9999,
          opacity: tip ? 1 : 0,
          transition: 'opacity 0.3s'
        }}>
          {tip}
        </div>
      )}
      {/* 直播画面 */}
      <video
        src={currentLive.video}
        autoPlay
        loop
        muted
        playsInline
        style={{width:'100%',height:'100vh',objectFit:'cover'}}
      />
      {/* 弹幕/消息区 - 添加引用和滚动样式 */}
      <div 
        ref={commentsRef}
        style={{
          position:'absolute',
          left:0,
          right:0,
          bottom:160,
          maxHeight:220,
          overflowY:'auto',
          zIndex:12,
          padding:'0 8px',
          scrollBehavior:'smooth', // 添加平滑滚动效果
          transition:'all 0.3s ease', // 添加过渡效果
          // 添加自定义滚动条样式
          scrollbarWidth:'thin',
          scrollbarColor:'#ff2d55 #333'
        }}
      >
        {messages.map(msg => (
          <div 
            key={msg.id} 
            style={{
              display:'flex',
              alignItems:'center',
              marginBottom:4,
              animation:'message-fade-in 0.3s ease', // 添加消息出现动画
              opacity:1
            }}
          >
            <img src={msg.avatar} alt="" style={{width:24,height:24,borderRadius:'50%',marginRight:6}} />
            <span style={{color:msg.levelColor,fontWeight:'bold',fontSize:13,marginRight:4}}>Lv{msg.level} {msg.nick}</span>
            <span style={{fontSize:14,marginRight:4}}>{msg.content}</span>
            {msg.gift && <span style={{marginLeft:4,fontSize:18}}>{msg.gift.icon} <span style={{fontSize:14}}>x{msg.gift.count}</span></span>}
          </div>
        ))}
        {/* 添加消息动画样式 */}
        <style>{`
          @keyframes message-fade-in {
            from { 
              opacity: 0; 
              transform: translateY(10px);
            }
            to { 
              opacity: 1; 
              transform: translateY(0);
            }
          }
          
          /* 自定义滚动条样式 - Webkit浏览器 */
          div::-webkit-scrollbar {
            width: 6px;
          }
          
          div::-webkit-scrollbar-track {
            background: #333;
            border-radius: 3px;
          }
          
          div::-webkit-scrollbar-thumb {
            background: #ff2d55;
            border-radius: 3px;
          }
        `}</style>
      </div>
      {/* 礼物动画队列 */}
      <div style={{position:'absolute',left:0,top:0,width:'100%',height:'100%',pointerEvents:'none',zIndex:20}}>
        {giftAnims.map((g) => (
          <div
            key={g.id}
            style={{
              position: 'absolute',
              left: '50%',
              top: '60%',
              transform: 'translate(-50%, -50%)',
              fontSize: 44,
              fontWeight: 'bold',
              color: '#ff2d55',
              animation: 'gift-fly 1.5s cubic-bezier(.4,0,.2,1)',
              display:'flex',alignItems:'center',background:'rgba(0,0,0,0.7)',borderRadius:24,padding:'8px 18px'
            }}
          >
            <img src={g.avatar} alt="" style={{width:32,height:32,borderRadius:'50%',marginRight:8}} />
            <span style={{fontSize:18,marginRight:8}}>{g.user}</span>
            {g.icon}
            <span style={{ fontSize: 20, marginLeft: 8 }}>{g.name}{g.count > 1 ? ` x${g.count}` : ''}</span>
          </div>
        ))}
        <style>{`
          @keyframes gift-fly {
            0% { transform: translate(-50%, 100%) scale(0.5); opacity: 0; }
            40% { transform: translate(-50%, -50%) scale(1.2); opacity: 1; }
            70% { transform: translate(-50%, -60%) scale(1); opacity: 1; }
            100% { transform: translate(-50%, -120%) scale(0.8); opacity: 0; }
          }
        `}</style>
      </div>
      {/* 右侧竖排按钮 */}
      <div style={{position:'absolute',right:8,top:'30%',zIndex:15,display:'flex',flexDirection:'column',gap:18}}>
        <button style={{background:'none',border:'none',color:'#ff2d55',fontSize:28}} onClick={handleLike}>❤️</button>
        <button style={{background:'none',border:'none',color:'#ff2d55',fontSize:28}} onClick={()=>setShowGiftPanel(true)}>🎁</button>
        <button style={{background:'none',border:'none',color:'#fff',fontSize:28}} onClick={()=>{
          if (!isFollowed) {
            alert('只有关注主播后才可以进行视频连线');
            return;
          }
          setShowLinkModal(true);
        }}>🔗</button>
      </div>
      {/* 点赞动画 */}
      {showLike && (
        <div style={{position:'absolute',right:30,bottom:180,fontSize:38,color:'#ff2d55',animation:'like-fly 0.8s',zIndex:30}}>❤️</div>
      )}
      <style>{`
        @keyframes like-fly {
          0% { transform: scale(1) translateY(0); opacity: 1; }
          100% { transform: scale(1.8) translateY(-120px); opacity: 0; }
        }
      `}</style>
      {/* 底部输入栏 */}
      <form style={{position:'absolute',left:0,right:0,bottom:0,background:'rgba(0,0,0,0.7)',padding:'10px 8px',display:'flex',alignItems:'center',zIndex:20}} onSubmit={handleSend}>
        <input placeholder="说点什么..." value={input} onChange={e=>setInput(e.target.value)}
          style={{flex:1,border:'none',borderRadius:16,padding:'8px 12px',fontSize:15,background:'#444',color:'#fff',marginRight:8}} />
        <button type="button" style={{background:'none',border:'none',fontSize:22,color:'#ff2d55',marginRight:6}}>😊</button>
        <button type="button" style={{background:'none',border:'none',fontSize:22,color:'#ff2d55',marginRight:6}} onClick={()=>setShowGiftPanel(true)}>🎁</button>
        {/* 添加自动评论开关按钮 */}
        <button 
          type="button" 
          style={{
            background: autoCommentEnabled ? '#ff2d55' : '#444',
            color: '#fff',
            border: 'none',
            borderRadius: 16,
            padding: '4px 10px',
            fontSize: 12,
            marginRight: 6,
            transition: 'background 0.3s'
          }}
          onClick={() => setAutoCommentEnabled(!autoCommentEnabled)}
        >
          {autoCommentEnabled ? '关闭自动评论' : '开启自动评论'}
        </button>
        <button type="submit" style={{background:'#ff2d55',color:'#fff',border:'none',borderRadius:16,padding:'6px 18px',fontSize:15,fontWeight:'bold'}}>发送</button>
      </form>
      {/* 礼物弹框 */}
      <GiftPanel
        visible={showGiftPanel}
        onClose={() => setShowGiftPanel(false)}
        onSend={handleSendGift}
        balance={balance}
        giftList={giftList}
        onRechargeClick={() => {
          setShowGiftPanel(false);
          setShowRecharge(true);
        }}
      />
      {/* 充值弹窗 */}
      <RechargeModal
        visible={showRecharge}
        onClose={() => setShowRecharge(false)}
        onRecharge={handleRecharge}
        balance={balance}
      />
      {/* 连线弹窗 */}
      {showLinkModal && (
        <div style={{position:'fixed',left:0,top:0,right:0,bottom:0,background:'rgba(0,0,0,0.45)',zIndex:100,display:'flex',alignItems:'center',justifyContent:'center'}}>
          <div style={{background:'#232323',borderRadius:'0.32rem',padding:'1.2rem 1.2rem 1rem 1.2rem',boxShadow:'0 4px 24px #0008',minWidth:'6rem',maxWidth:'90vw',textAlign:'center'}}>
            <div style={{fontWeight:'bold',fontSize:'1.2em',marginBottom:12}}>申请连线</div>
            <div style={{marginBottom:16}}>允许访问摄像头和麦克风，开始视频语音连线</div>
            <button style={{width:'100%',background:'#ff2d55',color:'#fff',border:'none',borderRadius:'0.32rem',padding:'0.12rem 0.32rem',fontSize:'1em',fontWeight:'bold',marginBottom:10}} onClick={handleStartLink}>允许并开始连线</button>
            <button style={{width:'100%',background:'#444',color:'#fff',border:'none',borderRadius:'0.32rem',padding:'0.12rem 0.32rem',fontSize:'1em'}} onClick={()=>setShowLinkModal(false)}>取消</button>
          </div>
        </div>
      )}
      {/* 连线小窗 */}
      {localStream && (
        <div style={{position:'absolute',right:'0.36rem',bottom:'1.2rem',zIndex:40,background:'#222d',borderRadius:'0.32rem',boxShadow:'0 4px 24px #0008',padding:'0.12rem 0.12rem 0.08rem 0.12rem',display:'flex',flexDirection:'column',alignItems:'center'}}>
          <video ref={videoRef} autoPlay muted playsInline style={{width:'3.2rem',height:'4.2rem',borderRadius:'0.32rem',background:'#000',boxShadow:'0 2px 12px #0008',marginBottom:'0.08rem'}} />
          <div style={{display:'flex',gap:'0.12rem',marginBottom:'0.04rem'}}>
            <button onClick={toggleVideo}>{videoEnabled ? '关摄像头' : '开摄像头'}</button>
            <button onClick={toggleAudio}>{audioEnabled ? '关麦' : '开麦'}</button>
            <button onClick={handleStopLink} style={{color:'#ff2d55'}}>挂断</button>
          </div>
        </div>
      )}
      {/* 确认离开直播间弹窗 */}
      {showExitConfirm && (
        <div style={{position:'fixed',left:0,top:0,right:0,bottom:0,background:'rgba(0,0,0,0.45)',zIndex:300,display:'flex',alignItems:'center',justifyContent:'center'}}>
          <div style={{background:'#232323',borderRadius:'0.32rem',padding:'1.2rem 1.2rem 1rem 1.2rem',boxShadow:'0 4px 24px #0008',minWidth:'6rem',maxWidth:'90vw',textAlign:'center',animation:'modal-in 0.3s ease'}}>
            <div style={{fontWeight:'bold',fontSize:'1.2em',marginBottom:12}}>确定要离开直播间吗？</div>
            <div style={{fontSize:'0.9em',color:'#aaa',marginBottom:18}}>离开后将无法继续观看当前直播</div>
            <div style={{display:'flex',gap:16,justifyContent:'center',marginTop:18}}>
              <button 
                style={{
                  background:'#ff2d55',
                  color:'#fff',
                  border:'none',
                  borderRadius:'0.32rem',
                  padding:'0.12rem 0.32rem',
                  fontSize:'1em',
                  fontWeight:'bold',
                  minWidth:80,
                  cursor:'pointer',
                  transition:'transform 0.2s, background 0.2s'
                }}
                onClick={confirmExit}
                onMouseOver={(e) => e.currentTarget.style.background = '#ff0040'}
                onMouseOut={(e) => e.currentTarget.style.background = '#ff2d55'}
                onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.95)'}
                onMouseUp={(e) => e.currentTarget.style.transform = 'scale(1)'}
              >
                确定离开
              </button>
              <button 
                style={{
                  background:'#444',
                  color:'#fff',
                  border:'none',
                  borderRadius:'0.32rem',
                  padding:'0.12rem 0.32rem',
                  fontSize:'1em',
                  minWidth:80,
                  cursor:'pointer',
                  transition:'transform 0.2s, background 0.2s'
                }}
                onClick={cancelExit}
                onMouseOver={(e) => e.currentTarget.style.background = '#555'}
                onMouseOut={(e) => e.currentTarget.style.background = '#444'}
                onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.95)'}
                onMouseUp={(e) => e.currentTarget.style.transform = 'scale(1)'}
              >
                继续观看
              </button>
            </div>
          </div>
          <style>{`
            @keyframes modal-in {
              from { opacity: 0; transform: scale(0.9); }
              to { opacity: 1; transform: scale(1); }
            }
          `}</style>
        </div>
      )}
      {/* 添加切换动画样式和淡入淡出动画 */}
      <style>{`
        @keyframes slide-up {
          0% { transform: translateY(0); opacity: 0; }
          100% { transform: translateY(-100%); opacity: 1; }
        }
        
        @keyframes slide-down {
          0% { transform: translateY(0); opacity: 0; }
          100% { transform: translateY(100%); opacity: 1; }
        }
        
        @keyframes fade-in {
          from { opacity: 0; transform: translate(-50%, -60%); }
          to { opacity: 1; transform: translate(-50%, -50%); }
        }
      `}</style>
    </div>
  );
}
 